package org.myy.learn.hot.finish.栈_1;

import java.util.Collections;
import java.util.LinkedList;

public class 字符串编码 {
    int i;
    public String decodeString(String s) {
        i = 0;
        LinkedList<String> deque = new LinkedList<>();
        //ToDo 流程中涉及i++操作
        while (i < s.length()){
            //1、数字情况
            if(Character.isDigit(s.charAt(i))){
                String dight = getDigits(s); //ToDo 可能非个位数
                deque.addLast(dight);
                //i++; //ToDo 在getDigits方法中已加过
            } else if (Character.isLetter(s.charAt(i)) || '[' == s.charAt(i)){  //ToDo  字符和字符串绝对不等，莫写出"[".equals(s.charAt(i))
                //2、字符 or "["
                deque.addLast(String.valueOf(s.charAt(i++)));
            } else {
                //3、"]"
                ++i;
                LinkedList<String> sub = new LinkedList<>();
                while (!"[".equals(deque.peekLast())){
                    //ToDo 找到对应"["
                    sub.addLast(deque.removeLast());
                }
                Collections.reverse(sub); //想用反转集合，所以使用LinkedList
                //移除"["
                deque.removeLast();
                String oneS = buildStr(sub);
                //ToDo 获取数字
                int digit = Integer.parseInt(deque.removeLast());
                StringBuffer sb = new StringBuffer();
                while (digit-- > 0){
                    sb.append(oneS);
                }
                //入栈
                deque.addLast(sb.toString());
            }
        }
        return buildStr(deque);
    }

    /**
     * 获取数字[可能非个位数]
     */
    private String getDigits(String s){
        StringBuffer sb = new StringBuffer();
        while(Character.isDigit(s.charAt(i))){
            sb.append(s.charAt(i++));
        }
        return sb.toString();
    }

    /**
     * 生成字符
     */
    private String buildStr(LinkedList<String> s){
        StringBuffer sb = new StringBuffer();
        for (String str : s){
            sb.append(str);
        }
        return sb.toString();
    }


}
